<template>
  <div class="charge-pile-manage">
    <div style="display: flex;">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="queryForm" class="mb-4">
        <el-form-item label="充电桩编号">
          <el-input v-model="queryForm.pileCode" placeholder="请输入充电桩编号" />
        </el-form-item>
        <el-form-item label="充电桩型号">
          <el-input v-model="queryForm.model" placeholder="请输入充电桩型号" />
        </el-form-item>
        <el-form-item label="设备厂商">
          <el-input v-model="queryForm.manufacturer" placeholder="请输入设备厂商" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="全部">
            <el-option label="空闲" value="0" />
            <el-option label="占用" value="1" />
            <el-option label="故障" value="2" />
            <el-option label="维护" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div>
        <div class="operation-buttons mb-4">
          <el-button type="success" @click="openAddDialog">+ 添加充电桩</el-button>
          <el-button type="primary">导入充电桩列表</el-button>
        </div>
      </div>
    </div>

    <!-- 充电桩表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="pileCode" label="充电桩编号" />
      <el-table-column prop="location" label="安装位置" />
      <el-table-column prop="model" label="充电桩型号" />
      <el-table-column prop="power" label="功率（kW）" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <span v-if="scope.row.status === 0">空闲</span>
          <span v-else-if="scope.row.status === 1">占用</span>
          <span v-else-if="scope.row.status === 2">故障</span>
          <span v-else>维护</span>
        </template>
      </el-table-column>
      <el-table-column prop="manufacturer" label="设备厂商" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="success" size="small" @click="restartPile(scope.row.id)">重置</el-button>
          <el-button type="primary" size="small" @click="editPile(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deletePile(scope.row.id)" :disabled="scope.row.status !== 0"
            class="delete-btn">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryForm.pageNum" :page-sizes="[10, 20, 50]" :page-size="queryForm.pageSize" :total="total"
      layout="total, sizes, prev, pager, next, jumper" />

    <!-- 编辑弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="编辑充电桩" width="50%" @close="dialogVisible = false">
      <el-form :model="form" label-width="120px">
        <el-form-item label="充电桩编号">
          <el-input v-model="form.pileCode" disabled />
        </el-form-item>
        <el-form-item label="安装位置">
          <el-input v-model="form.location" />
        </el-form-item>
        <el-form-item label="充电桩型号">
          <el-input v-model="form.model" />
        </el-form-item>
        <el-form-item label="功率（kW）">
          <el-input v-model.number="form.power" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="空闲" :value="0" />
            <el-option label="占用" :value="1" />
            <el-option label="故障" :value="2" />
            <el-option label="维护" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备厂商">
          <el-input v-model="form.manufacturer" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加弹窗（含 ECharts 地图选点） -->
    <el-dialog :visible.sync="addDialogVisible" title="添加充电桩" width="70%" @close="onAddDialogClose">
      <el-form :model="addForm" label-width="120px" class="add-form-with-map">
        <div class="form-left">
          <el-form-item label="充电桩编号" prop="pile_code">
            <el-input v-model="addForm.pile_code" placeholder="请输入充电桩编号" />
          </el-form-item>

          <!-- 修改：地址输入 + 定位按钮，替代点击地图取点 -->
          <!-- 修改：地址仅用于展示与提交，不再强制转换为经纬度 -->
          <el-form-item label="安装位置" prop="location">
            <div style="display:flex; gap:8px; width:100%">
              <el-input v-model="addForm.location" placeholder="请输入南京市内的详细街道、门牌号" />
              <el-button size="mini" type="primary" @click="geocodeLocation">根据地址定位</el-button>
            </div>
            <div class="map-tip">输入南京市内详细地址后自动定位，地图无需点击。</div>
          </el-form-item>

          <!-- 修改：占位文案改为自动定位填充 -->
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model.number="addForm.latitude" placeholder="定位后自动填充纬度" />
          </el-form-item>

          <el-form-item label="经度" prop="longitude">
            <el-input v-model.number="addForm.longitude" placeholder="定位后自动填充经度" />
          </el-form-item>

          <el-form-item label="充电桩型号" prop="model">
            <el-input v-model="addForm.model" placeholder="请输入型号" />
          </el-form-item>

          <el-form-item label="功率（kW）" prop="power">
            <el-input v-model.number="addForm.power" placeholder="请输入功率" />
          </el-form-item>

          <el-form-item label="设备厂商" prop="manufacturer">
            <el-input v-model="addForm.manufacturer" placeholder="请输入厂商" />
          </el-form-item>

          <el-form-item label="安装时间" prop="install_time">
            <el-date-picker v-model="addForm.install_time" type="datetime" placeholder="选择安装时间"
              format="yyyy-MM-dd HH:mm:ss" />
          </el-form-item>
        </div>

        <!-- 地图区域 -->
        <div class="form-right">
          <div class="map-header">
            <!-- 修改：地图仅显示南京，交互为地址驱动定位 -->
            <span>南京市地图（输入地址自动定位）</span>
            <el-button size="mini" @click="centerToDefault" icon="el-icon-refresh-right"></el-button>
            <el-button size="mini" @click="clearMapPoint">清除标记</el-button>
          </div>
          <div ref="echartsMap" class="echarts-map"></div>
          <div class="map-tip">点击地图任意位置设置安装位置，经纬度会自动填充到表单。</div>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import * as echarts from 'echarts' // 确保项目已安装 echarts

export default {
  name: 'ChargePileManage',
  data() {
    return {
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        pileCode: '',
        model: '',
        manufacturer: '',
        status: ''
      },
      tableData: [],
      total: 0,
      dialogVisible: false,
      form: {},
      addDialogVisible: false,
      addForm: {
        pile_code: '',
        location: '',
        latitude: null,
        longitude: null,
        model: '',
        power: null,
        manufacturer: '',
        install_time: ''
      },
      // 地图相关
      echartsInstance: null,
      mapPoint: null, // { lng, lat }
      // 修改：本地离线地址索引缓存
      localGeoIndex: null
    }
  },
  mounted() {
    this.fetchPileList()
  },
  watch: {
    //地址输入后自动定位（防抖由用户手动触发按钮更可控；如需自动，请取消注释）
    'addForm.location'(val) {
      if (val && val.length >= 5) {
        this._autoGeoTimer && clearTimeout(this._autoGeoTimer)
        this._autoGeoTimer = setTimeout(() => this.geocodeLocation(), 600)
      }
    }
  },
  methods: {
    // 修改：离线地址定位（不调用外部 API）- 定位后在地图打点并自动填写经纬度
    async geocodeLocation() {
      if (!this.addForm.location) {
        return this.$message.warning('请先输入南京市内的详细地址')
      }
      const loading = this.$loading({ lock: true, text: '正在定位(本地)...', spinner: 'el-icon-loading' })
      try {
        await this.ensureLocalGeoIndex()
        const input = this.addForm.location.trim()
          .replace(/江苏省|南京市/g, '')
          .replace(/\s+/g, '')

        // 1) 尝试在本地索引中做包含匹配，按命中长度评分
        let bestItem = null
        let bestScore = 0
        for (const item of (this.localGeoIndex || [])) {
          const name = (item.name || '').replace(/\s+/g, '')
          if (!name) continue
          const score = input.length > 0 && name.includes(input) ? input.length : 0
          if (score > bestScore) {
            bestScore = score
            bestItem = item
          }
        }
        // 2) 允许“关键字 空格 关键字”分词命中叠加
        if (!bestItem && input.length > 0) {
          const tokens = input.split(/[,，、;；.。\-\s]/).filter(Boolean)
          for (const item of (this.localGeoIndex || [])) {
            const name = (item.name || '')
            let hits = 0
            for (const t of tokens) { if (t && name.includes(t)) hits++ }
            if (hits > bestScore) { bestScore = hits; bestItem = item }
          }
        }
        if (bestItem) {
          // 在地图上标记并回填经纬度
          this.setMapPoint(Number(bestItem.lng), Number(bestItem.lat))
          return
        }
        // 3) 兜底：支持用户直接粘贴“经度,纬度”或“纬度,经度”
        const coordMatch = this.addForm.location.match(/(-?\d+\.?\d*)\s*[,，\s]\s*(-?\d+\.?\d*)/)
        if (coordMatch) {
          let a = Number(coordMatch[1]); let b = Number(coordMatch[2])
          // 简单判断经纬顺序（经度应在 105~121 附近，纬度在 30~34 附近）
          let lng = a, lat = b
          if (Math.abs(a) <= 40 && Math.abs(b) >= 100) { lng = b; lat = a }
          // 在地图上标记并回填经纬度
          this.setMapPoint(lng, lat)
          return
        }
        this.$message.error('未在本地索引中匹配到该地址，请输入更具体的街道门牌或直接填写经纬度')
      } catch (e) {
        this.$message.error('本地定位出错，请检查 public/nanjing_local_index.json 是否存在')
      } finally {
        loading.close()
      }
    },

    // 修改：仅居中地图显示，不写回表单
    centerMapTo(lng, lat) {
      if (!this.echartsInstance) return
      try {
        this.echartsInstance.setOption({ geo: { center: [lng, lat], zoom: 13 } })
      } catch (_) { }
    },

    // 修改：懒加载本地索引文件（优先街道索引，回退到简版索引）
    async ensureLocalGeoIndex() {
      if (Array.isArray(this.localGeoIndex) && this.localGeoIndex.length > 0) return
      const baseUrl = (process.env && process.env.BASE_URL ? process.env.BASE_URL : '/')
      const tryLoad = async (name) => {
        const res = await fetch(baseUrl + name)
        if (!res.ok) throw new Error('404')
        return await res.json()
      }
      try {
        // 优先使用更细的街道索引
        this.localGeoIndex = await tryLoad('nanjing_streets.json')
      } catch (_) {
        // 回退到简版地标索引
        this.localGeoIndex = await tryLoad('nanjing_local_index.json')
      }
    },
    handleFilter() {
      this.queryForm.pageNum = 1
      this.fetchPileList()
    },
    resetQuery() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
        pileCode: '',
        model: '',
        manufacturer: '',
        status: ''
      }
      this.fetchPileList()
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchPileList()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.fetchPileList()
    },
    async fetchPileList() {
      const loading = this.$loading({ lock: true, text: '加载中...', spinner: 'el-icon-loading' })
      try {
        const response = await request({
          url: '/pile/',
          method: 'get',
          params: this.queryForm
        })
        if (response.code == 200) {
          this.tableData = response.data.records || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.data.msg || '获取数据失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '网络错误')
      } finally {
        loading.close()
      }
    },
    async restartPile(id) {
      // const loading = this.$loading({ lock: true, text: '操作中...', spinner: 'el-icon-loading' })
      // try {
      //   const userId = this.$store?.state?.user?.id || localStorage.getItem('userId') || null
      //   if (!userId) {
      //     this.$message.warning('未获取到用户ID，已使用演示ID=1 发起操作。可在登录后写入 userId 到 localStorage。')
      //   }
      //   const response = await request({
      //     url: `/pile/remoteControlPile/${id}`,
      //     method: 'post',
      //     data: { controlType: 1, userId: userId || 1 }
      //   })
      //   if (response.code === 200) {
      //     this.$message.success(response.msg || '操作成功')
      //     this.fetchPileList()
      //   } else {
      //     this.$message.error(response.msg || '操作失败')
      //   }
      // } catch (error) {
      //   console.error(error)
      //   this.$message.error(error.response?.data?.msg || '操作失败')
      // } finally {
      //   loading.close()
      // }
      this.$message.warning('待开发！')
    },
    editPile(row) {
      this.form = { ...row }
      this.dialogVisible = true
    },
    async deletePile(id) {
      try {
        await this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const loading = this.$loading({ lock: true, text: '删除中...', spinner: 'el-icon-loading' })
        try {
          const response = await request({
            url: `/pile/deletePile/${id}`,
            method: 'delete'
          })
          if (response.code === 200) {
            this.$message.success(response.data.msg || '删除成功')
            this.fetchPileList()
          } else {
            this.$message.error(response.data.msg || '删除失败')
          }
        } catch (error) {
          const errorMsg = error.response?.data?.msg || '删除失败'
          if (errorMsg.includes('外键约束') || errorMsg.includes('parent row')) {
            this.$message.error('该充电桩存在关联记录，无法删除')
          } else {
            this.$message.error(errorMsg)
          }
        } finally {
          loading.close()
        }
      } catch {
        this.$message.info('已取消删除')
      }
    },
    async saveForm() {
      if (!this.form.id) {
        return this.$message.error('编辑数据异常，缺少充电桩ID');
      }
      if (!this.form.location || !this.form.model) {
        return this.$message.error('安装位置和型号不能为空');
      }
      if (this.form.power == null) {
        return this.$message.error('请填写功率');
      }
      const loading = this.$loading({ lock: true, text: '保存中...', spinner: 'el-icon-loading' })
      try {
        const response = await request({
          url: `/pile/updatePile/${this.form.id}`,
          method: 'put',
          data: {
            location: this.form.location,
            model: this.form.model,
            power: this.form.power != null ? Number(this.form.power) : null,
            manufacturer: this.form.manufacturer,
            // 后端通常期望数字状态：0空闲 1占用 2故障 3维护
            status: this.form.status != null ? Number(this.form.status) : null
          }
        })
        if (response.code === 200) {
          this.$message.success('保存成功')
          this.dialogVisible = false
          this.fetchPileList()
        } else {
          this.$message.error(response.msg || '保存失败')
        }
      } catch (error) {
        this.$message.error(error.response?.data?.msg || '保存失败')
      } finally {
        loading.close()
      }
    },

    // ---------- 添加弹窗 / 地图逻辑 ----------
    openAddDialog() {
      this.addDialogVisible = true
      this.resetAddForm()
      this.$nextTick(() => {
        this.initEchartsMap()
      })
    },
    onAddDialogClose() {
      // 关闭弹窗时销毁图表实例，释放资源
      if (this.echartsInstance) {
        this.echartsInstance.off('click')
        this.echartsInstance.dispose()
        this.echartsInstance = null
      }
      window.removeEventListener('resize', this.resizeEcharts)
      this.addDialogVisible = false
    },
    resetAddForm() {
      this.addForm = {
        pile_code: '',
        location: '',
        latitude: null,
        longitude: null,
        model: '',
        power: null,
        manufacturer: '',
        install_time: null
      }
      this.mapPoint = null
    },
    // 修改：初始化地图仅加载南京市（无则回退全国），不再绑定点击取点
    initEchartsMap() {
      // 确保容器存在
      const dom = this.$refs.echartsMap
      if (!dom) return

      // 如果已有实例先 dispose
      if (this.echartsInstance) {
        this.echartsInstance.off('click')
        this.echartsInstance.dispose()
        this.echartsInstance = null
      }

      this.echartsInstance = echarts.init(dom)
      this.echartsInstance.showLoading()

      // 修改：优先加载南京市 GeoJSON，若不存在则回退全国
      const baseUrl = (process.env && process.env.BASE_URL ? process.env.BASE_URL : '/')
      const loadJson = (url) => fetch(url).then(res => { if (!res.ok) throw new Error('HTTP ' + res.status); return res.json() })
      const nanjingUrl = baseUrl + 'nanjing.json'
      const chinaUrl = baseUrl + 'china.json'

      // 修改：封装地图初始化（注册 map + 配置中心与缩放，自动适配边界）
      const initMapWith = (mapName, geojson, center, zoom) => {
        try {
          if (!echarts.getMap(mapName)) {
            echarts.registerMap(mapName, geojson)
          }
        } catch (e) {
          console.error('注册地图失败: ', e)
        }
        // 修改：根据 GeoJSON 计算边界与合适的视图
        const view = this.computeViewFromGeoJSON(geojson, this.$refs.echartsMap)
        const useCenter = view ? view.center : center
        const useZoom = view ? view.zoom : zoom
        const bounding = view ? view.boundingCoords : null
        const option = {
          geo: {
            map: mapName,
            roam: true,
            center: useCenter,
            zoom: useZoom,
            label: { show: false },
            itemStyle: { areaColor: '#f3f8ff', borderColor: '#aaa' },
            emphasis: { itemStyle: { areaColor: '#e6f2ff' } },
            // 修改：限制漫游在边界内
            ...(bounding ? { boundingCoords: bounding } : {})
          },
          series: [
            { type: 'scatter', coordinateSystem: 'geo', symbolSize: 12, data: [] }
          ]
        }
        this.echartsInstance.setOption(option)

        window.addEventListener('resize', this.resizeEcharts)
      }

      // 修改：优先南京，其次全国
      loadJson(nanjingUrl)
        .then(geojson => initMapWith('nanjing', geojson, [118.796877, 32.060255], 10))
        .catch(() => loadJson(chinaUrl).then(geojson => initMapWith('china', geojson, [104.0, 35.0], 4)))
        .catch(err => {
          console.error('地图数据加载失败，请确认 public/nanjing.json 或 public/china.json 是否存在: ', err)
          this.$message && this.$message.error('地图数据加载失败，请联系管理员')
        })
        .finally(() => { this.echartsInstance && this.echartsInstance.hideLoading() })
    },
    // 修改：从 GeoJSON 计算中心/缩放/边界，近似贴合视图（离线）
    computeViewFromGeoJSON(geojson, domEl) {
      try {
        if (!geojson || !geojson.features || geojson.features.length === 0) return null
        let minLng = Infinity, minLat = Infinity, maxLng = -Infinity, maxLat = -Infinity
        for (const f of geojson.features) {
          const g = f.geometry
          if (!g) continue
          const coords = g.type === 'Polygon' ? [g.coordinates] : g.type === 'MultiPolygon' ? g.coordinates : []
          for (const poly of coords) {
            for (const ring of poly) {
              for (const pt of ring) {
                const lng = pt[0], lat = pt[1]
                if (lng < minLng) minLng = lng
                if (lat < minLat) minLat = lat
                if (lng > maxLng) maxLng = lng
                if (lat > maxLat) maxLat = lat
              }
            }
          }
        }
        if (!isFinite(minLng) || !isFinite(minLat) || !isFinite(maxLng) || !isFinite(maxLat)) return null
        const center = [(minLng + maxLng) / 2, (minLat + maxLat) / 2]
        // 以墨卡托近似估算缩放：把纬度转为墨卡托 y，基于容器尺寸计算
        const mercY = (lat) => {
          const rad = lat * Math.PI / 180
          return Math.log(Math.tan(Math.PI / 4 + rad / 2))
        }
        const dx = maxLng - minLng
        const dy = mercY(maxLat) - mercY(minLat)
        const el = domEl || this.$refs.echartsMap
        const w = (el && el.clientWidth) || 800
        const h = (el && el.clientHeight) || 400
        // 在 ECharts 中，zoom=1 约等于把世界(360°)映射到某个基准宽；经验系数取 3.2 做近似
        const zx = w / (dx * 3.2)
        const zy = h / (dy * 3.2)
        let zoom = Math.max(1, Math.min(20, Math.min(zx, zy)))
        // 给南京加一点放大系数让边界更贴边
        zoom = zoom * 0.95
        const boundingCoords = [[minLng, maxLat], [maxLng, minLat]]
        return { center, zoom, boundingCoords }
      } catch (_) {
        return null
      }
    },
    // 修改：设置地图点位时，自动居中并提高缩放到街道级
    setMapPoint(lng, lat) {
      this.mapPoint = { lng, lat }
      // 在图上画点
      if (!this.echartsInstance) return
      this.echartsInstance.setOption({
        series: [
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            symbolSize: 14,
            symbol: 'pin',
            label: { show: false },
            itemStyle: { color: '#ff6666' },
            data: [[lng, lat]]
          }
        ],
        // 可视化中心（若需要自动居中）
        geo: {
          center: [lng, lat],
          zoom: 13
        }
      })

      // 修改：经纬度保留 7 位小数并写入表单（不改写安装位置文本）
      const lngFixed = Number(lng.toFixed(7))
      const latFixed = Number(lat.toFixed(7))
      this.addForm.longitude = lngFixed
      this.addForm.latitude = latFixed
      // 不覆盖 addForm.location，保持用户输入的街道/门牌
    },
    // 修改：默认定位到南京市中心
    centerToDefault() {
      // 将地图中心设为某个默认位置（可根据需要改）
      if (!this.echartsInstance) return
      // 南京市中心
      const defaultCenter = [118.796877, 32.060255]
      try {
        // 可尝试使用 setOption 的 geo.center 或者 convertToPixel/convertFromPixel
        this.echartsInstance.setOption({
          geo: { center: defaultCenter, zoom: 10 }
        })
      } catch (e) {
        // 某些场景无效则忽略
      }
    },
    clearMapPoint() {
      this.mapPoint = null
      this.addForm.latitude = null
      this.addForm.longitude = null
      this.addForm.location = ''
      if (this.echartsInstance) {
        this.echartsInstance.setOption({
          series: [{ data: [] }]
        })
      }
    },

    resizeEcharts() {
      if (this.echartsInstance) this.echartsInstance.resize()
    },

    async submitAddForm() {
      // 修改：表单校验改为后端要求的字段：pileCode、installTime 必填；建议 location 也填写
      if (!this.addForm.pile_code) {
        return this.$message.warning('请填写充电桩编号')
      }
      if (!this.addForm.install_time) {
        return this.$message.warning('请选择安装时间')
      }
      if (!this.addForm.location) {
        return this.$message.warning('请输入安装位置（街道/门牌）')
      }
      if (this.addForm.latitude == null || this.addForm.longitude == null) {
        return this.$message.warning('请先定位获取经纬度（根据地址定位或点击地图）')
      }

      const loading = this.$loading({ lock: true, text: '提交中...', spinner: 'el-icon-loading' })
      try {
        // 修改：将前端下划线字段映射为后端驼峰字段
        const formatLocalDateTime = (d) => {
          if (!d) return null
          const pad = (n) => (n < 10 ? '0' + n : '' + n)
          const y = d.getFullYear()
          const m = pad(d.getMonth() + 1)
          const day = pad(d.getDate())
          const hh = pad(d.getHours())
          const mm = pad(d.getMinutes())
          const ss = pad(d.getSeconds())
          return `${y}-${m}-${day}T${hh}:${mm}:${ss}`
        }
        const payload = {
          pileCode: this.addForm.pile_code,
          location: this.addForm.location,
          latitude: this.addForm.latitude ?? null,
          longitude: this.addForm.longitude ?? null,
          model: this.addForm.model,
          power: this.addForm.power,
          manufacturer: this.addForm.manufacturer,
          installTime: formatLocalDateTime(this.addForm.install_time),
          status: 0
        }
        const response = await request({ url: '/pile/addPile', method: 'post', data: payload })
        if (response.code === 200) {
          this.$message.success('添加成功')
          this.addDialogVisible = false
          // 清理地图实例
          if (this.echartsInstance) {
            this.echartsInstance.off('click')
            this.echartsInstance.dispose()
            this.echartsInstance = null
            window.removeEventListener('resize', this.resizeEcharts)
          }
          this.fetchPileList()
        } else {
          this.$message.error(response.data.msg || '添加失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '网络错误')
      } finally {
        loading.close()
      }
    }
  },
  beforeDestroy() {
    if (this.echartsInstance) {
      this.echartsInstance.dispose()
      window.removeEventListener('resize', this.resizeEcharts)
    }
  }
}
</script>

<style scoped>
.charge-pile-manage {
  padding: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: flex-end;
}

::v-deep .delete-btn.is-disabled {
  background-color: #f5f5f5 !important;
  border-color: #dcdcdc !important;
  color: #bfbfbf !important;
  cursor: not-allowed;
}

::v-deep .delete-btn.is-disabled:hover {
  background-color: #f5f5f5 !important;
  border-color: #dcdcdc !important;
  color: #bfbfbf !important;
}

/* 添加弹窗 - 布局 */
.add-form-with-map {
  display: flex;
  gap: 16px;
}

/* 左侧表单占比 */
.add-form-with-map .form-left {
  flex: 1 1 360px;
  min-width: 320px;
}

/* 右侧地图占比 */
.add-form-with-map .form-right {
  flex: 1 1 520px;
  min-width: 420px;
  display: flex;
  flex-direction: column;
}

.echarts-map {
  height: 420px;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  margin-top: 8px;
}

/* 地图头部按钮 */
.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 小提示 */
.map-tip {
  margin-top: 8px;
  color: #888;
  font-size: 12px;
}
</style>
